<?php
/**
 * tx009 网站文章发布系统
 */
//**** 初始化一些目录信息 ****//

    define('ROOT_PATH', dirname(__FILE__) . '/');
    define('LIB_PATH', ROOT_PATH . 'lib/');
    define('IMG_PATH', ROOT_PATH . 'img/');
    
    require ROOT_PATH . 'config.php';  // 导入配置文件
    require LIB_PATH  . 'function.php';  // 导入类库方法
    
    $time = date('m-d',time());
    
    // 先获取医院信息
    $csvTabName = array(
        'hosName'          => '医院简拼',
        'HospitalCity'     => '医院地区',
        'HospitalName'     => '医院名称',
        'HospitalFullName' => '医院全称',
        'HospitalAddr'     => '医院地址',
        'HosAbbrAddr'      => '医院短地址',
        'HospitalTel'      => '医院电话号码',
        'HospitalQQ'       => '医院QQ',
        'HospitalWecha'    => '医院微信',
        'DoctorName'       => '医生姓名',
        'operHours'        => '工作时间',
        'mobileSite'       => '手机站地址',
        'swtid'            => '商务通ID'
    );

    // 获取 CSV内容
    $jsonArr = csv2json(dirname(__FILE__) . '/hosTag.csv', $csvTabName);
    $hosRepKey = array();
    foreach ($jsonArr as $value) {
        // 分解医生信息
        $value['DoctorName'] = explode('/', $value['DoctorName']);
        // 分解手机站地址
        $value['mobileSite'] = explode('/', $value['mobileSite']);
        $hosRepKey[$value['hosName']] = $value;
    }
    
    print_f("======天下网发文章系统======\n启动时间: " . date('Y-m-d H:i:s') . "\n\n");
    // 初始化
    $ch = curl_init(); 
    curl_setopt($ch, CURLOPT_HEADER, FALSE);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_POST, TRUE );
    curl_setopt($ch, CURLOPT_TIMEOUT, 65);
    
    $csv = '';
    $baidupush = array();
    foreach($sessions as $session ){
        
    //==========================================初始化用户信息======================================
        print_f("当前用户:".$session['qq']."\n\n");
        
        $titlefile = LIB_PATH."title/".$session['name']."_title.txt";
        $titles   = txttoarray($titlefile);
        $count    = getTitleId($titlefile);
        $jianjies = txttoarray(LIB_PATH."descrip/".$session['name']."_descrip.txt");
        
        $cookieVerify = "PHPSESSID=".$session['id'];
        curl_setopt($ch, CURLOPT_COOKIE, $cookieVerify);
        
        $endi = 0;
        $errorc = 0;
        $imglist = scandir(IMG_PATH.$session['hosType'].'/');
        unset($imglist[0]);
        unset($imglist[1]);
        
        $i = $count;
        
        for(;$i < ($count+$config['postsum']+$endi); $i++){
            
            if(empty($titles[$i])){
                print_f('文章遍历完毕');
                break;
            }
                
            $title = $titles[$i];
            
            print_f("当前标题:".$title."\n");
    //========================================测试标题======================================
            $postField = array('title'  => $title,
                                'class_id'=>$config['class_id'],
                                'city_id'=> $session['city_id'],
                                'con'    => getarticle(rand($config['pidmin'],$config['pidmax']),$session,$title),
                                'jianjie'=> "    ".$jianjies[array_rand($jianjies)],
                                'verify' => "",
                                'keys'   =>  $titles[array_rand($titles)],
                                'pic[]'  =>  new CURLFile(IMG_PATH.$session['hosType'].'/'. $imglist[array_rand($imglist)],'image/jpeg'),
                            );
            curl_setopt($ch, CURLOPT_URL, "http://www.tx009.com/Fabu/index/class_id/16");
            curl_setopt($ch, CURLOPT_POSTFIELDS,$postField); 
            $result = curl_exec($ch);
            
            $result = str_replace(array("\r\n", "\r", "\n"), "",$result);
            
            preg_match('/验证码错误/',$result,$error);
            
            if(empty($error[0])){
                preg_match('/error">(.*?)</',$result,$error);
                print_f($error[1]);echo "\n";
                $endi++;
                $errorc++;
                if($errorc>20 || preg_match('(小黑屋|天下币|先登录)', $error[1])){
                    break;
                } 
                continue;
            }
            
    //==========================================获取验证码图片======================================
    
            curl_setopt($ch, CURLOPT_URL, "http://www.tx009.com/Public/verify_code/");
            $rs = curl_exec($ch);
            
            // 把验证码在本地生成
            @file_put_contents(ROOT_PATH."verify.jpg",$rs);
            
    //==========================================识别验证码======================================
            $postFields = array('username'=> $ysdm['username'],
                                'password'=> $ysdm['password'],
                                'typeid'  => $ysdm['typeid'],
                                'timeout' => 60,
                                'softid'  => $ysdm['softid'],
                                'softkey' => $ysdm['softkey'],
                                'image'   =>  new CURLFile(ROOT_PATH.'verify.jpg'),
                            );
            curl_setopt($ch, CURLOPT_URL,$ysdm['posturl']);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
            $verify_code = json_decode(curl_exec($ch),true);
            
    //==========================================发布文章======================================
    
            $postField['verify'] = $verify_code['Result'];
            
            curl_setopt($ch, CURLOPT_URL, "http://www.tx009.com/Fabu/index/class_id/16");
            curl_setopt($ch, CURLOPT_POSTFIELDS,$postField); 
            $result = curl_exec($ch);
       
    //==========================================效验无效验证码======================================
            $result=str_replace(array("\r\n", "\r", "\n"), "",$result);
            preg_match('/验证码错误/',$result,$error);
            
            if(!empty($error[0])){
                
            print_f("验证码错误重发\n");
                $postFields = array('username' => $ysdm['username'],
                                    'password' => md5($ysdm['password']),
                                    'softid'   => $ysdm['softid'],
                                    'softkey'  => $ysdm['softkey'],
                                    'id'       => $verify_code['Id'],
                                );
                curl_setopt($ch, CURLOPT_URL,$ysdm['reporterror']);
                curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
                curl_exec($ch);
                $i--;
            }else{
            
    //==========================================效验无效表单数据======================================
    
                preg_match('/发布成功了/',$result,$succ);
                if(empty($succ[0])){
                    preg_match('/error">(.*?)</',$result,$error);
                    print_f($error[1]);echo "\n";
                    $endi++;
                    $errorc++;
                    if($errorc>20 || preg_match('(小黑屋|天下币|先登录)', $error[1])){
                        break;
                    } 
                }
            }
        }
    //=========================================捕获发布信息==========================================
    
        curl_setopt($ch, CURLOPT_URL, "http://www.tx009.com/fabu/lists_shang");
        $content = curl_exec($ch);
        $content = str_replace(array("\r\n", "\r", "\n"), "",$content);
        preg_match_all('/<tr(.*?)<\/tr>/',$content,$content);
        
        unset($content[0][0]);
        unset($content[0][1]);
        $csvdata = array();
        foreach($content[0] as $key => $v){
            preg_match('/href=" (.*?)">(.*?)<\/a><\/td>    <td class="center"> 男科<\/td>    <td class="center"> '.$time.'(.*?)<\/td>/',$v,$data);
            
            if(!empty($data)){
                $baidupush[] = "http://www.tx009.com".$data[1];
                $csvdata[] = array($data[2],"http://www.tx009.com".$data[1],$time.$data[3]);
            }
        }
        $csv .= outputCsv($csvdata,$session['qq']);
        
        // 保存本次的ID
        setTitleId($titlefile,$i);
    }
    file_put_contents(ROOT_PATH.'csv/'.$time.".csv" , $csv);
    curl_close($ch);
    
    do_baiduPush($baidupush);
    
    print_f("==========任务结束==========" . date('Y-m-d H:i:s'));
    
    /**
     * 将数组动态输出至 csv 文件
     * @param array $data 二维数组
     * @param string $filename 文件名
     */
    function outputCsv($data,$qq) {
        $str =  $qq.",\r\n";
        foreach ($data as $fields) {
            foreach ($fields as $key => $value) {
                $str .= $value . ',';
            }
            $str .= "\r\n";
        }
        return $str;
    }
    
    //执行百度推送计划
    function do_baiduPush($all_list){
        $pushFail = array();//初始化 
        $pustNum  = count($all_list);
        $pust_i = 0;
        foreach ($all_list as $postUrl) {
            $ret = baidu_push($postUrl);
            $pust_i += $ret ? 1 : 0;
            if($ret){
             print_f("\t{$postUrl}\t[OK]\n", 1);
            }else{
             print_f("\t{$postUrl}\t[NO]\n", 1);
             $pushFail[] = $postUrl;
            }
            sleep(1);
        }
        $push_e = $pustNum - $pust_i;
        print_f("成功 {$pust_i} 条 , 失败 {$push_e} 条\n");
        
        if (!empty($pushFail)){
            print_r("\n休息30s后，推送失败的链接将再次推送\n");
            sleep(30);
            do_baiduPush($pushFail);
        }else{
            print_r("所有链接推送完毕...\n");
        }
    }